//
//  EFAUtySelDevTypeTVC.m
//  efairy
//
//  Created by XiangDongMBP on 2017/8/25.
//  Copyright © 2017年 East. All rights reserved.
//

#import "EFAUtySelDevTypeTVC.h"
#import "GlobalHeader.h"
#import "UIColor+XDHex.h"
#import "EFAModel.h"
#import "MBProgressHUD+XDPrompt.h"

@interface EFAUtySelDevTypeTVC ()
@property (nonatomic, assign) EFAUtySelDevTypeTVCType viewType;
@property (nonatomic, strong) UIBarButtonItem *cancelBarBtnItem;
@property (nonatomic, strong) UIBarButtonItem *sureBarBtnItem;

@property (nonatomic, readonly) NSArray *sysDevTypeArray;   ///< 所有的数据类型
@property (nonatomic,   strong) NSArray *devTypeArray;      ///< 设备类型的数据
@property (nonatomic, readonly) NSArray *dataArray;         ///< 方便界面使用的数据
@property (nonatomic, readonly) NSString *keyName;          ///< 访问dictionary的key
@property (nonatomic,   strong) NSIndexPath *selIndexPath;  ///< 选中的indexPath

@end

static NSString *const kReuseCellId = @"UITableViewCell";

@implementation EFAUtySelDevTypeTVC
#pragma mark - life cycle
- (instancetype)initWithViewType:(EFAUtySelDevTypeTVCType)viewType {
    self = [super init];
    if (self) {
        _viewType = viewType;
    }
    return self;
}
- (instancetype)init {
    NSAssert(NO, @"use initWithViewType");
    return nil;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initNavigationBar];
    [self initSubViews];
}

- (void)initNavigationBar {
    NSArray *titleArray = @[@"系统类型", @"设备类型"];
    self.navigationItem.title = titleArray[self.viewType];
    if (self.navigationController.viewControllers.firstObject == self) {
        self.navigationItem.leftBarButtonItem = self.cancelBarBtnItem;
    }
    self.navigationItem.rightBarButtonItem = self.sureBarBtnItem;
    [self.sureBarBtnItem setEnabled:NO];
    self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:nil action:nil];
}

- (void)initSubViews {
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:kReuseCellId];
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 67.0;
    self.tableView.alwaysBounceVertical = YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kReuseCellId forIndexPath:indexPath];
    cell.textLabel.textColor = [UIColor xd_colorWithHex:0x222222];
    cell.textLabel.font = [UIFont systemFontOfSize:14];
    if (indexPath.row < self.dataArray.count) {
        cell.textLabel.text = self.dataArray[indexPath.row][self.keyName];
    }
    if (self.viewType == EFAUtySelDevTypeTVCSys) {
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    } else {
        if (self.selIndexPath && self.selIndexPath.section == indexPath.section && self.selIndexPath.row == indexPath.row) {
            cell.accessoryType = UITableViewCellAccessoryCheckmark;
        } else {
            cell.accessoryType = UITableViewCellAccessoryNone;
        }
    }
    return cell;
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 14.9;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.1;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (self.viewType == EFAUtySelDevTypeTVCSys) {
        // 跳转到设备类型选择
        if (indexPath.row < self.sysDevTypeArray.count) {
            NSDictionary *dic = self.sysDevTypeArray[indexPath.row];
            [self jumpToSelDeviceTypeWithSysId:[dic[@"system_type_id"] integerValue]];
        }
    } else {
        // 勾选
        self.selIndexPath = indexPath;
        [tableView reloadData];
    }
}

#pragma mark - event response
- (void)cancelBarBtnTapped:(UIBarButtonItem *)item {
    [self dismissViewControllerAnimated:YES completion:nil];
}
- (void)sureBarBtnTapped:(UIBarButtonItem *)item {
    if (self.viewType == EFAUtySelDevTypeTVCSys) {
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"系统类型错误"];
        return;
    }
    
    if (!self.selIndexPath) {
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"请选择设备类型"];
        return;
    }
    
    if (self.selIndexPath.row < self.devTypeArray.count) {
        NSDictionary *dic = self.devTypeArray[self.selIndexPath.row];
        NSInteger device_type_id = [dic[@"device_type_id"] integerValue];
        [self dismissViewControllerAnimated:YES completion:^{
            if (self.successHandle) {
                self.successHandle(device_type_id);
                self.successHandle = nil;
            }
        }];
    }
}

#pragma mark - private methods
- (void)jumpToSelDeviceTypeWithSysId:(NSInteger)system_type_id {
    EFAUtySelDevTypeTVC *vc = [[EFAUtySelDevTypeTVC alloc] initWithViewType:EFAUtySelDevTypeTVCDev];
    vc.system_type_id = system_type_id;
    vc.successHandle = self.successHandle;
    [self showViewController:vc sender:nil];
}

#pragma mark - network request
#pragma mark - getters and setters
- (UIBarButtonItem *)cancelBarBtnItem {
    if (!_cancelBarBtnItem) {
        _cancelBarBtnItem = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(cancelBarBtnTapped:)];
    }
    return _cancelBarBtnItem;
}
- (UIBarButtonItem *)sureBarBtnItem {
    if (!_sureBarBtnItem) {
        _sureBarBtnItem = [[UIBarButtonItem alloc] initWithTitle:@"完成" style:UIBarButtonItemStylePlain target:self action:@selector(sureBarBtnTapped:)];
        NSDictionary * norAttr = @{NSForegroundColorAttributeName: [UIColor xd_colorWithHex:EFAGlobalColorDarkGreen],
                                   NSFontAttributeName: [UIFont systemFontOfSize:15]};
        [_sureBarBtnItem setTitleTextAttributes:norAttr forState:UIControlStateNormal];
        NSDictionary * disableAttr = @{NSForegroundColorAttributeName: [UIColor xd_colorWithHex:EFAGlobalColorDarkGreen alpha:0.5],
                                       NSFontAttributeName: [UIFont systemFontOfSize:15]};
        [_sureBarBtnItem setTitleTextAttributes:disableAttr forState:UIControlStateDisabled];
    }
    return _sureBarBtnItem;
}

- (NSArray *)sysDevTypeArray {
    return [EFADeviceProtocolModel sharedInstance].sysDevTypeArray;
}

- (NSArray *)devTypeArray {
    if (!_devTypeArray) {
        _devTypeArray = [[EFADeviceProtocolModel sharedInstance] deviceTypeArrayWithSystemTypeId:_system_type_id];
    }
    return _devTypeArray;
}

- (NSArray *)dataArray {
    return (self.viewType == EFAUtySelDevTypeTVCSys) ? self.sysDevTypeArray : self.devTypeArray;
}

- (NSString *)keyName {
    return (self.viewType == EFAUtySelDevTypeTVCSys) ? @"system_type_name" : @"device_type_name";
}

- (void)setSelIndexPath:(NSIndexPath *)selIndexPath {
    _selIndexPath = selIndexPath;
    if (!_sureBarBtnItem.isEnabled) {
        [_sureBarBtnItem setEnabled:YES];
    }
}

@end
